// 文件上传
import express from 'express'
import path from 'path'
import fs from "fs";

let router = express.Router()

router.post('/', (req, res) => {
    if (!req.files || req.files.length === 0)
        return res.json({
        code: 201,
        msg: '未发现文件信息'
    })
    let filesPath = []
    for (let i = 0; i < req.files.length; i++) {
        let file = req.files[i]
        /*获取文件扩展名*/
        const extension = path.extname(file.originalname)
        /*根据扩展名决定存储目录*/
        let targetDir;
        switch (extension) {
            case '.jpg':
            case '.jpeg':
            case '.png':
            case '.gif':
            case '.webp':
            case '.bmp':
                targetDir = 'file/image/';
                break;
            case '.doc':
            case '.docx':
            case '.dotx':
            case '.dot':
            case '.rtf':
            case '.html':
            case '.xml':
            case '.odt':
                targetDir = 'file/word/';
                break;
            case '.ppt':
            case '.pptx':
            case '.ppsx':
            case '.potx':
                targetDir = 'file/ppt/';
                break;
            case '.xlsx':
            case '.xls':
            case '.csv':
            case '.xlsm':
            case '.xltx':
                targetDir = 'file/excel/';
                break;
            case '.pdf':
                targetDir = 'file/pdf/'
                break;
            case '.mp4':
                targetDir = 'file/video/';
                break;
            case '.mp3':
                targetDir = 'file/audio/';
                break;
            default:
                targetDir = 'file/other/';
                break;
        }

        // 确保目标目录存在
        if (!fs.existsSync(targetDir)) {
            fs.mkdirSync(targetDir, {recursive: true});
        }

        /*生成新的文件名，避免文件名冲突*/
        const newFileName = `${Date.now()}-${file.originalname}`
        const targetPath = path.join(targetDir, newFileName)
        /*将文件移动到目标目录*/
        fs.rename(file.path, targetPath, (err) => {
            if (err) return res.json({
                code: 201,
                msg: '文件移动失败'
            })
            filesPath.push(targetPath.replace(/\\/g, '/'))
            if (i === req.files.length - 1) return res.json({
                code: 200,
                msg: '文件上传成功',
                files: filesPath
            })
        })
    }
})

export default router
